<style scoped>
.user-search {
  margin-top: 20px;
}

.center {
  text-align: center;
}

.title {
  font-size: 26px;
}

.el-drawe-body {
  padding: 20px;
}

</style>

<template>
  <div>

    <el-drawer :title="drawerTitle()" :visible.sync="drawer" :direction="'rtl'" :before-close="handleClose">
      <template v-if="drawerType == 'nextQuestion'">
        <div style="height: 100%; width: 100%; padding: 20px">
          <el-radio @input="nextQuestionSelectHandler" :disabled="selectOption.orderNum == item.orderNum" :readonly="selectOption.orderNum == item.orderNum"  v-model="selectOption.target" :label="item.orderNum" v-for="(item, index) in questions" :key="index" style="display: table; margin-top: 10px;">
            {{ item.orderNum + ". " + item.name }}
          </el-radio>

          <el-button type="info" size="small" plain style="margin-top: 20px" @click="toEnd(selectOption)">直接结束</el-button>
          <el-button type="warning" size="small" plain style="margin-top: 20px" @click="toEndAndGiveUp(selectOption)">结束并放弃样本</el-button>
        </div>

      </template>

      <template v-if="drawerType == 'editOption'">
        <el-form ref="optionForm" :model="selectOption" label-width="80px">
          <el-form-item label="问题序号" prop="orderNum">
            <el-input v-model="selectOption.orderNum" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="选项文本" prop="name">
            <el-input v-model="selectOption.name"></el-input>
          </el-form-item>
          <el-form-item label="需要备注" prop="hasRemark">
            <el-switch v-model="selectOption.hasRemark" :active-value="1" :inactive-value="0" active-color="#13ce66"></el-switch>
          </el-form-item>
          <el-form-item label="是否排他" prop="exclusivity">
            <el-switch v-model="selectOption.exclusivity" :active-value="1" :inactive-value="0" active-color="#13ce66"></el-switch>
          </el-form-item>
          <el-form-item label="忽略配额" prop="ignoreNum">
            <el-switch v-model="selectOption.ignoreNum" :active-value="1" :inactive-value="0" active-color="#13ce66"></el-switch>
          </el-form-item>
          <el-form-item label="放弃样本" prop="giveUp">
            <el-switch v-model="selectOption.giveUp" :active-value="1" :inactive-value="0" active-color="#13ce66"></el-switch>
          </el-form-item>
          <el-form-item label="配额数量" prop="configration">
            <el-input v-model="selectOption.configration" type="number"></el-input>
          </el-form-item>
          <el-form-item label="选项分数" prop="configration">
            <el-input v-model="selectOption.score" type="number"></el-input>
          </el-form-item>
          <el-form-item label="下一问题" prop="type">
            <p style="margin: 0 0 0 15px;">{{nextQuestionTextFilter(selectOption.target)}}</p>
          </el-form-item>
        </el-form>
      </template>


      <template v-if="drawerType == 'editQuestion'">
        <el-form ref="qustionForm" :model="selectQuestion" label-width="80px">
          <el-form-item label="问题序号" prop="orderNum">
            <el-input v-model="selectQuestion.orderNum" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="问题标题" prop="name">
            <el-input v-model="selectQuestion.name"></el-input>
          </el-form-item>
          <el-form-item label="问题类型" prop="type">
            <p style="margin: 0 0 0 15px;">{{selectQuestion.type && selectQuestion.type.desc}}</p>
          </el-form-item>
          <el-form-item label="最少选择" prop="minSelect">
            <el-input v-model="selectQuestion.minSelect" :disabled="selectQuestion.type !== 2"></el-input>
          </el-form-item>
          <el-form-item label="最多选择" prop="orderNum">
            <el-input v-model="selectQuestion.maxSelect" :disabled="selectQuestion.type !== 2"></el-input>
          </el-form-item>
        </el-form>
      </template>

    </el-drawer>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/base/survey/index' }">问卷管理</el-breadcrumb-item>
      <el-breadcrumb-item>问卷设计</el-breadcrumb-item>
    </el-breadcrumb>

    <el-row style="margin-top: 25px">
      <el-col :span="6">
        <el-card class="box-card">
          <div>
            <span>快捷操作: &nbsp;</span>
            <el-button size="small" @click="addSingleSelect">单选</el-button>
            <el-button size="small" @click="addMultySelect">多选</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6" :offset="12">
        <el-card class="box-card">
          <div style="text-align: center">
            <el-button size="small" @click="save" type="success" plain>保存</el-button>
            <el-button size="small" @click="back" type="info" plain>返回列表</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" class="user-search">
        <el-card class="box-card">
          <div class="grid-content bg-purple-dark center title">
            <span>{{ survey.name }}</span>
          </div>
          <div class="grid-content bg-purple-dark center">
            <span>开场语: {{ survey.startShow }}</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" style="margin-top: 25px">
        <el-card class="box-card">
          <el-empty v-if="!questions || questions.length === 0" description="暂无数据"></el-empty>
          <el-table v-if="questions && questions.length > 0" :cell-class-name="tableCellClassHandler" :data="questions" row-key="mrid" @row-dblclick="expandOrCloseRow"
                    style="width: 100%;margin-bottom: 20px;" border ref="designTable" :header-row-style="{width: '100%', color: 'darkorange'}"
                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column prop="orderNum" label="序号" width="80">
              <template slot-scope="scope">
                <b v-if="scope.row.children">{{ scope.row.orderNum}}</b>
                <p v-if="!scope.row.children">{{ scope.row.orderNum}}</p>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="标题(文本)">
              <template slot-scope="scope">
                <b v-if="scope.row.children">{{ scope.row.name}}</b>
                <p v-if="!scope.row.children">{{ scope.row.name}}</p>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="题目类型" width="80">
              <template slot-scope="scope">
                <b>{{ scope.row.type && scope.row.type.desc}}</b>
              </template>
            </el-table-column>
            <el-table-column prop="minSelect" label="最小选择" width="80" align="center">
              <template slot-scope="scope">
                <b>{{ scope.row.minSelect}}</b>
              </template>
            </el-table-column>
            <el-table-column prop="maxSelect" label="最大选择" width="80" align="center">
              <template slot-scope="scope">
                <b>{{ scope.row.maxSelect}}</b>
              </template>
            </el-table-column>

            <el-table-column prop="hasRemark" label="备注" width="50" align="center">
              <template slot-scope="scope">
                <p>{{ scope.row.hasRemark | yesNo }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="ignoreNum" label="忽略配额" width="80" align="center">
              <template slot-scope="scope">
                <p> {{ scope.row.ignoreNum | yesNo }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="configration" label="配额" width="50" align="center"/>
            <el-table-column prop="score" label="得分" width="50" align="center"/>

            <el-table-column prop="exclusivity" label="排他性" width="70" align="center">
              <template slot-scope="scope">
                {{ scope.row.exclusivity | yesNo }}
              </template>
            </el-table-column>

            <el-table-column prop="target" label="跳题" width="70" align="center">
              <template slot-scope="scope">
                <el-link v-if="scope.row.target" style="font-size: 24px" type="success" @click="setNextQuestion(scope.row)">{{ scope.row.target }}</el-link>
                <p v-if="scope.row.type === undefined && scope.row.target === null" style="color: #dd6161"  @click="setNextQuestion(scope.row)">结束</p>
              </template>
            </el-table-column>

            <el-table-column prop="giveUp" label="放弃" width="70" align="center">
              <template slot-scope="scope">
                <p>{{ scope.row.giveUp | yesNo }}</p>
              </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="300">
              <template slot-scope="scope">
                <el-dropdown size="small" split-button type="primary" trigger="click" @click="handleEdit(scope.$index, scope.row)">
                  编辑
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :icon="'el-icon-top'" :divided="true" @click.native="toUp(scope.$index, scope.row)">上移</el-dropdown-item>
                    <el-dropdown-item :icon="'el-icon-bottom'" :divided="true" @click.native="toDown(scope.$index, scope.row)">下移</el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.children" :icon="'el-icon-plus'" :divided="true" @click.native="addOption(scope.$index, scope.row)">选项</el-dropdown-item>
                    <el-dropdown-item :icon="'el-icon-delete-solid'" :divided="true" @click.native="deleteItem(scope.$index, scope.row)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="24" class="user-search">
        <el-card class="box-card">
          <div class="grid-content bg-purple-dark center">
            <span>结束语: {{ survey.endShow }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>

</template>

<script>
import Pagination from '../../../components/Pagination'
import {surveydetail, surveyDesignSave, surveyDesign} from '../../../api/baseMG'

const uuid = require('uuid');

export default {
  data() {
    return {
      survey: {},
      questions: [],
      drawerType: '',         // 抽屉功能
      drawer: false,          // 抽屉打开开关
      selectOption: {},       // 当前选择的选项
      selectQuestion: {}      // 当前选择的问题
    }
  },
  created() {
    this.detail(this.$route.query.id);
    this.getSurveyDesign(this.$route.query.id);
  },
  // 注册组件
  components: {
    Pagination
  },
  filters: {
    surveyType(data) {
      if (data.type === 1) {
        return "单选题"
      }
      if (data.type === 2) {
        return "多选题"
      }
    }
  },
  methods: {
    back() {
      this.$router.push('/base/survey/index');
    },
    nextQuestionTextFilter(data) {
      for (let i = 0; i < this.questions.length; i++) {
        if(this.questions[i]['orderNum'] === data) {
          return data + ". " + this.questions[i]['name'];
        }
      }
      return '结束';
    },
    getSurveyDesign(id) {
      surveyDesign({id: id}).then(resp => {
        this.questions =  resp.data.sort((a, b) => a.orderNum - b.orderNum);
      })
    },
    handleClose() {
      this.selectQuestion = {};
      this.selectOption = {};
      this.drawer = false;
    },
    // 下一题选中时间
    nextQuestionSelectHandler(v) {
      this.selectOption.orderNum = v;
    },
    // 抽屉的标题
    drawerTitle() {
      if (this.drawerType === 'nextQuestion') {
        return '选择跳题';
      }

      if (this.drawerType === 'editOption') {
        return '修改选项';
      }

      if (this.drawerType === 'editQuestion') {
        return '修改问题';
      }
    },
    // 弹出抽屉 选择下一题
    setNextQuestion(row) {
      this.selectOption = row;
      this.drawer = true;
      this.drawerType = 'nextQuestion';
    },
    tableCellClassHandler({row, column, rowIndex, columnIndex}) {
      if (row[column.property] !== undefined) {
        return 'empty_cell_color';
      }
      if (row[column.property] != null) {
        return 'empty_cell_color';
      }
      return '';
    },
    handleEdit(index, row) {
      this.drawer = true;
      // 判断是否包含childrn 元素， 包含则是编辑问题
      if(row.hasOwnProperty('children')) {
        this.selectQuestion = row;
        return this.drawerType = 'editQuestion';
      }
      this.selectOption = row;
      this.drawerType = 'editOption';
    },
    deleteItem: function (index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for (let i = 0; i < this.questions.length; i++) {
          let question = this.questions[i];
          if(question.mrid === row.mrid) {
            // 删除的是问题
            this.questions.splice(i, 1);
            return this.deleteQuestionCallback(question);
          }
          let children = question.children;
          for (let j = 0; j < children.length; j++) {
            // 删除的是选项
            let child = children[j];
            if(child.mrid === row.mrid) {
              children.splice(j, 1);
              return this.deleteOptionCallback(children);
            }
          }
        }
      })
    },
    //添加一个默认的多选题
    addMultySelect() {
      // 设置之前的下一题
      if (this.questions && this.questions.length > 0) {
        let que = this.questions[this.questions.length - 1];
        let children = que.children;
        if (children && children.length > 0) {
          for (let i = 0; i < children.length; i++) {
            if (!children[i].target) {
              children[i].target = this.getNextQuestionOrderNum();
            }
          }
        }
      }
      this.questions.push(
        {
          mrid: uuid.v1(),
          name: '多选题',
          orderNum: this.getNextQuestionOrderNum(),
          minSelect: 1,
          maxSelect: 4,
          type: {
            code: 2,
            desc: '多选题',
            value: 2
          },
          children: [{
            mrid: uuid.v1(),
            name: '选项一',
            orderNum: 1,
            hasRemark: 0,
            ignoreNum: 0,
            score: 0,
            configration: 0,
            exclusivity: 0,
            target: null,
            giveUp: 0
          }, {
            mrid: uuid.v1(),
            name: '选项二',
            orderNum: 2,
            hasRemark: 0,
            ignoreNum: 0,
            score: 0,
            configration: 0,
            exclusivity: 0,
            target: null,
            giveUp: 0
          }, {
            mrid: uuid.v1(),
            name: '选项三',
            orderNum: 3,
            hasRemark: 0,
            ignoreNum: 0,
            score: 0,
            configration: 0,
            exclusivity: 0,
            target: null,
            giveUp: 0
          }, {
            mrid: uuid.v1(),
            name: '选项四',
            orderNum: 4,
            hasRemark: 0,
            ignoreNum: 0,
            score: 0,
            configration: 0,
            exclusivity: 0,
            target: null,
            giveUp: 0
          }]
        })
    },
    // 添加单选题
    addSingleSelect() {
      // 设置之前的下一题
      if (this.questions && this.questions.length > 0) {
        let que = this.questions[this.questions.length - 1];
        let children = que.children;
        if (children && children.length > 0) {
          for (let i = 0; i < children.length; i++) {
            if (!children[i].target) {
              children[i].target = this.getNextQuestionOrderNum();
            }
          }
        }
      }
      this.questions.push(
        {
          mrid: uuid.v1(),
          name: '单选题',
          orderNum: this.getNextQuestionOrderNum(),
          minSelect: 1,
          maxSelect: 1,
          type: {
            code: 1,
            desc: '单选题',
            value: 1
          },
          children: [{
            mrid: uuid.v1(),
            name: '选项一',
            orderNum: 1,
            hasRemark: 0,
            ignoreNum: 0,
            score: 0,
            configration: 0,
            exclusivity: 1,
            target: null,
            giveUp: 0
          }, {
            mrid: uuid.v1(),
            name: '选项二',
            orderNum: 2,
            hasRemark: 0,
            ignoreNum: 0,
            score: 0,
            configration: 0,
            exclusivity: 1,
            target: null,
            giveUp: 0
          }, {
            mrid: uuid.v1(),
            name: '选项三',
            orderNum: 3,
            hasRemark: 0,
            ignoreNum: 0,
            score: 0,
            configration: 0,
            exclusivity: 1,
            target: null,
            giveUp: 0
          }, {
            mrid: uuid.v1(),
            name: '选项四',
            orderNum: 4,
            hasRemark: 0,
            ignoreNum: 0,
            score: 0,
            configration: 0,
            exclusivity: 1,
            target: null,
            giveUp: 0
          }]
        }
      )
    },
    getNextQuestionOrderNum() {
      return this.questions.length + 1;
    },
    detail(id) {
      if (id) {
        surveydetail(id).then(resp => {
          this.survey = resp.data;
        })
      }
    },
    expandOrCloseRow(row, column, event) {
      if(!row.expanded) {
        row.expanded = true;
        this.$refs.designTable.toggleRowExpansion(row, true);
      } else {
        row.expanded = false;
        this.$refs.designTable.toggleRowExpansion(row, false);
      }
    },
    save() {
      let params = JSON.parse(JSON.stringify(this.questions));
      for (const question of params) {
        if(!(!isNaN(parseFloat(question.id)) && isFinite(question.id))) {
          delete question['id'];
        }
        for (const c of question.children) {
          if(!(!isNaN(parseFloat(c.id)) && isFinite(c.id))) {
            delete c['id'];
          }
        }
      }
      surveyDesignSave({survey: this.survey, questions: params}).then(resp => {
        if (resp.success) {
          this.$message({
            type: 'success',
            message: resp.msg
          });

          // 重载本页面
          this.reloadPage();
        }
      })
    },
    reloadPage() {
      this.questions = [];
      this.drawerType = '';         // 抽屉功能
      this.drawer = false;          // 抽屉打开开关
      this.selectOption = {};      // 当前选择的选项
      this.selectQuestion = {};
      this.getSurveyDesign(this.$route.query.id);
    },
    // 删除问题回调函数
    deleteQuestionCallback(question) {
      this.reOrder(this.questions);
      this.removeToQuestion(question);
    },
    // 删除选项回调函数
    deleteOptionCallback(options) {
      this.reOrder(options);
    },
    // 重新排序
    reOrder(source) {
      source = source.sort((a, b) => a.orderNum - b.orderNum);
      let tem = [];

      for (let i = 0; i < source.length; i++) {
        let s = source[i];
        s.orderNum = i+1;
        tem.push(s);
      }
      source = tem;
    },
    // 移出跳转到某一题的选项跳转信息
    removeToQuestion(q) {
      for (const question of this.questions) {
        if(question.children) {
          for (let i = 0; i < question.children.length; i++) {
            if(question.children[i].target === q.orderNum) {
              // 如果是最后一题
              if(this.questions.indexOf(question) > this.questions.length - 2) {
                question.children[i].target = null;
              } else {
                question.children[i].target = question.orderNum + 1;
              }
            }
          }
        }
      }
    },
    toUp(index, row) {
      if(this.lastQuestion(row)) {
        // 有选项 => 是问题
        if(row.hasOwnProperty("children")) {
          let lastQ = this.lastQuestion(row);

          let t = lastQ.orderNum;
          lastQ.orderNum = row.orderNum;
          row.orderNum = t;
          this.updateOptionsForQ(row);
          this.updateOptionsForQ(lastQ);
          this.reOrder(this.questions);
        } else {
          // 无选项 => 是选项
          let option = this.lastOption(row);
          let t = row.orderNum;
          row.orderNum = option.orderNum;
          option.orderNum = t;
          this.reOrder(this.ownQuestion(row).children);
        }
      } else {
        this.$message({
          type: 'error',
          message: '已经是最上层了'
        });
      }

    },
    toDown(index, row) {
      if(row.hasOwnProperty("children")) {
        // 有选项 => 是问题
        let nextQ = this.nextQuestion(row);
        if(nextQ) {
          let t = row.orderNum;
          row.orderNum = nextQ.orderNum;
          nextQ.orderNum = t;
          this.reOrder(this.questions);
          this.updateOptionsForQ(row);
          this.updateOptionsForQ(nextQ);
        } else {
          this.$message({
            type: 'error',
            message: '已经是最下了'
          });
        }
      } else {
        let option = this.nextOption(row);
        let t = row.orderNum;
        row.orderNum = option.orderNum;
        option.orderNum = t;
        this.reOrder(this.ownQuestion(row).children);
      }
    },
    updateOptionsForQ(q) {
      let nextQ = this.nextQuestion(q);
      // 判断这个题目是不是最后一题
      if(nextQ) {
        // 如果有下一题  本题的target 是下一题
        for (let i = 0; i < q.children.length; i++) {
          let child = q.children[i];
          child.target = nextQ.orderNum;
        }
      } else {
        // 最后一题没有跳转
        if(q.children) {
          for (let i = 0; i < q.children.length; i++) {
            let child = q.children[i];
            child.target = null;
          }
        }
      }
    },
    swapArray(arr, index1, index2) {
      arr[index1] = arr.splice(index1, 1, arr[index2])[0]
      return arr;
    },
    lastQuestion(q) {
      if(q.orderNum == 1) {
        return null;
      }
      for (const question of this.questions) {
        if(question.orderNum === q.orderNum - 1) {
          return question;
        }
      }
    },
    nextQuestion(q) {
      if(q.orderNum === this.questions.length) {
        return null;
      }
      for (const question of this.questions) {
        if(question.orderNum == q.orderNum + 1) {
          return question;
        }
      }
    },
    lastOption(o) {
      if(o.orderNum == 1) {
        return null;
      }
      for (let i = 0; i < this.questions.length; i++) {
        let question = this.questions[i];
        if(question.children) {
          for (let j = 0; j < question.children.length; j++) {
            let child = question.children[j];
            if(child.id === o.id) {
              return question.children[j-1] ? question.children[j-1] : null;
            }
          }
        }
      }
    },
    nextOption(o) {
      for (let i = 0; i < this.questions.length; i++) {
        let question = this.questions[i];
        if(question.children) {
          for (let j = 0; j < question.children.length; j++) {
            let child = question.children[j];
            if(child.id === o.id) {
              return question.children[j+1] ? question.children[j+1] : null;
            }
          }
        }
      }
    },
    ownQuestion(o) {
      for (let i = 0; i < this.questions.length; i++) {
        let question = this.questions[i];
        if(question.children) {
          for (let j = 0; j < question.children.length; j++) {
            let child = question.children[j];
            if(child.id === o.id) {
              return question;
            }
          }
        }
      }
    },
    addOption(index, row) {
      if(row.type.value === 1) {
        row.children.push({
          mrid: uuid.v1(),
          name: '新增选项',
          orderNum: row.children.length + 1,
          hasRemark: 0,
          ignoreNum: 0,
          score: 0,
          configration: 0,
          exclusivity: 1,
          target: row.orderNum + 1 <= this.questions.length ? row.orderNum + 1 : null,
          giveUp: 0
        })
      }

      if(row.type.value === 2) {
        row.children.push({
          mrid: uuid.v1(),
          name: '新增选项',
          orderNum: row.children.length + 1,
          hasRemark: 0,
          ignoreNum: 0,
          score: 0,
          configration: 0,
          exclusivity: 0,
          target: null,
          giveUp: 0
        })
      }
    },
    toEnd(o) {
      o.target = null;
    },
    toEndAndGiveUp(o) {
      o.target = null;
      o.giveUp = 1;
    }
  }
}
</script>

